/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.redis.converter;

import cn.hutool.core.util.PrimitiveArrayUtil;
import com.iwindplus.boot.util.ProtostuffUtil;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * Protobuf 序列化.
 *
 * @param <T> 泛型
 * @author zengdegui
 * @since 2024/01/21
 */
@Slf4j
public class ProtostuffRedisSerializer<T> implements RedisSerializer<T> {

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (Objects.isNull(t)) {
            return null;
        }

        try {
            return ProtostuffUtil.toJsonBytes(t);
        } catch (Exception ex) {
            throw new SerializationException("Protobuf Could not serialize: " + ex.getMessage(), ex);
        }
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (PrimitiveArrayUtil.isEmpty(bytes)) {
            return null;
        }

        try {
            return ProtostuffUtil.parseBytes(bytes);
        } catch (Exception ex) {
            throw new SerializationException("Protobuf Could not deserialize: " + ex.getMessage(), ex);
        }
    }
}
